#!/bin/sh
pwd='Admin1234!'

function clean(){
  #echo "clean ..."
  rm -rf $pwdf
  #kill -9 $(lsof -i:5432|grep ssh|awk '{print $2}')
  kill -9 $(ps aux|grep "$PORT_LOCAL:localhost:5432"|grep -v grep|awk '{print $2}') >/dev/null 2>&1
  exit
}
trap 'clean' SIGINT SIGKILL
if [ "$*" = "-h" ];then
	echo "pg IP"
	echo "pg 129.55|10.206.129.55"
	echo
	echo "Install pgcli to local: pip install pgcli"
    echo
	exit 0
fi
pwd='Admin1234!'
if [ "$*" = "-l" ];then
  pwd='uw+De6qN'
fi
ipr=$*
cnt=$(echo -n $ipr|sed 's/\./\n/g'|wc -l)
if [ $cnt -eq 1 ];then
  ip="10.206."$ipr
else
 ip=$ipr
fi
ipcalc  -cs $ip
if [ $? -ne 0 ];then
  echo "Invalid IP Address, exit "
  exit 1
fi

PORT_LOCAL=$$
# get a free port
while : ; do
   t=$(lsof -i:$PORT_LOCAL|wc -l)
   if [ $t -eq 0 ];then
         break
   fi
       PORT_LOCAL=$((PORT_LOCAL+1))
done 
echo "Connect $ip from port $PORT_LOCAL ..."

# set key
key='/tmp/ddan_id_rsa'
cat > ${key} <<HERE
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEArgTuf6daR+8kxrCrXIMmGcGhu4gVOm6h9BXlE6ZDGTGDuIQJ
4EE+kMaBL/5O37DeyopAqTAZf6SsAtlKXb+kX7mDoxvMaP+yxnz6DM3xPSvLtZR+
OKig21fyuCggefp/kE+FEptYT3kdevcabw0zpDiiWpaF5CPfYcPdLatrjiUksn/S
WWpQTLm8McCDJ11SZHmmIFTlfdNQYAFE8AgcdXQi1NiATyQPRxshzTAMbNEzgbD0
P1nIUqRwQcZyS71GWH+w5bKdz+oIijElqTrhwfiXpSXO8hZ69xqMBru3chDpVu3Q
kRRFCPcqF2bfVxM30HctqBtV+8ZbMhlRK7mZawIDAQABAoIBAQCmuErXOjqgmFkf
krtaUrv6CS0uQd40sTGwbBmgjbXTOU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vB+XgPcOn+9gRJw2Wo8P+tHYWU5WW0V/bTmdoBBZmNv+CSGxGEAVEF7iTOB/qa
8FHVcHAy04dRtmOJbya5SRA5uhSCpWxMT10tIAQfBFn9AkZKfqyMyw==
-----END RSA PRIVATE KEY-----
HERE
chmod 400 $key
# auto login ssh by passwd
pwdf=$(mktemp)
echo "echo $pwd" > $pwdf
chmod a+x $pwdf
export SSH_ASKPASS=$pwdf
[ "$DISPLAY" ] || export DISPLAY; DISPLAY=
# ssh local forward
setsid ssh  -i $key -fqtN -L $PORT_LOCAL:localhost:5432 $ip -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null &

# port is reay
c=0
while [ $c -lt 5 ];do
   t=$(lsof -i:$PORT_LOCAL|wc -l)
   if [ $t -eq 0  ];then
       sleep 1
   else
     c=$((c+1))
   fi
done

# pgcli connection
pgcli --prompt "\\u@$ip:\\d> " postgres://dtasuser:uw+De6qN@localhost:$PORT_LOCAL/dtasdb 
clean
#function clean(){
#  echo "clean ..."
#  rm -rf $pwdf
#  #kill -9 $(lsof -i:5432|grep ssh|awk '{print $2}')
#  kill -9 $(ps aux|grep "$PORT_LOCAL:localhost:5432"|grep -v grep|awk '{print $2}') >/dev/null 2>&1
#}

